package com.wf.demo.job.pojo;

import com.wf.demo.info.dao.DeviceDAO;
import com.wf.demo.info.pojo.Device;
import com.wf.demo.info.service.DeviceService;
import com.wf.demo.info.util.StatisticalUtil;
import com.wf.demo.job.service.TimeOfDeviceService;
import com.wf.demo.job.util.RedisUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @Auther: wf
 * @Date: 2019/12/2 14:03
 * @Description:
 */
@Component
public class ScheduledTasks {
    @Autowired
    DeviceDAO deviceDAO;
    @Autowired
    DeviceService deviceService;
    @Autowired
    TimeOfDeviceService timeOfDeviceService;
    @Autowired
    RedisUtil redisUtil;
    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    private AtomicInteger integer = new AtomicInteger(0);

   /* @Scheduled(cron = "0/30 * * * * ? ")
    public void doJobByCron() throws InterruptedException {
        /*int index = integer.incrementAndGet();
        System.out.println(String.format("[%s] %s doJobByCron start @ %s", index, Thread.currentThread(), LocalTime.now()));
        // 这儿随机睡几秒，方便查看执行效果
        TimeUnit.SECONDS.sleep(new Random().nextInt(5));
        System.out.println(String.format("[%s] %s doJobByCron end   @ %s", index, Thread.currentThread(), LocalTime.now()));*/
        /*int index = integer.incrementAndGet();
        System.out.println(String.format("[%s] %s doJobByCron start @ %s", index, Thread.currentThread(), LocalTime.now()));
        deviceService.monitorIsOnline(10); //间隔十分钟置为离线
        System.out.println(String.format("[%s] %s doJobByCron end   @ %s", index, Thread.currentThread(), LocalTime.now()));
    }
    /**
     * fixedRate：固定速率执行。每5秒执行一次。
     */
    /*@Scheduled(fixedRate = 5000)
    public void reportCurrentTimeWithFixedRate() {
        log.info("Current Thread : {}", Thread.currentThread().getName());
        log.info("Fixed Rate Task : The time is now {}", dateFormat.format(new Date()));
    }*/

    /**
     *功能描述  每个月的第一天0时0分0秒执行，对每个设备创建一个表记录它在这个月的在线时间
     * @author wf
     * @date 2019/12/11
     * @param
     * @return void
     */
    //表示在每月的1日的凌晨1点执行任务
    @Scheduled(cron = "0 0 1 1 * ?")
    public void setDeviceOnlineTimeOfMonthByCron() throws InterruptedException{
        List<Device> devices=deviceDAO.findAll(); //对所有设备
            for(Device device:devices){
                TimeOfDevice timeOfDevice=new TimeOfDevice();
                timeOfDevice.setCreatTime(LocalDate.now()); //每月第一天
                timeOfDevice.setDevice(device); //绑定设备
                timeOfDeviceService.add(timeOfDevice);
        }
    }
    /**
     *功能描述  每天定时统计设备的总数量，在线数量，不在线数量，报警等信息到缓存中
     *            cache文件夹是 statisticalUtil
     * @author wf
     * @date 2019/12/17
     * @param
     * @return void
     */
    //表示在每天的凌晨0点执行任务
    @Scheduled(cron = "0 0 1 * * ?")
    public void saveReids() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate=LocalDate.now();
        String ss= df.format(localDate);
        StatisticalUtil statisticalUtil=deviceService.getAllStatisticalInfo();
        redisUtil.set("statisticalUtil"  + ":"+ "statisticalUtil-"+ ss,statisticalUtil);//存储，文件夹名是statisticalUtil
        StatisticalUtil result = (StatisticalUtil) redisUtil.get("statisticalUtil"  + ":"+ "statisticalUtil-"+ ss); //读取
        System.out.println(result.toString());

    }

    /**
     * fixedRate：固定速率执行。每xxx秒执行一次。
     * 120s =2min
     * 遍历所有设备，如果上一次的在线时间和当前时间差值为xx分钟，说明设备已经离线
     */
    @Scheduled(fixedRate = 1000*120)
    public void monitorIsOnlineWithFixedRate() {
        deviceService.monitorIsOnline(30);  //timeInterval (时间差值，单位分钟min),这里30分钟
        log.info("定时2min遍历设备是否已经离线");
        log.info("Fixed Rate Task : The time is now {}", dateFormat.format(new Date()));
    }


}
